﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

using AttributeRouting;
using AttributeRouting.Web.Mvc;
using Newtonsoft.Json.Linq;
using LuxDiner.Model.Accounts;
using LuxDiner.Logic.Accounts;
using LuxDiner.Model.Results;

namespace LuxDiner.Web.Management.Controllers
{
    public class GlobalApiController : ApiController
    {
        [Route("UserLogin")]
        [HttpGet, HttpPost]
        public JsonResult<bool> Login(JObject request)
        {
            var errinfo = "登陆失败，原因：";
            try
            {
                //var checkCode = request.Value<string>("checkCode");
                //if (checkCode != Common.CheckCode) throw new ApplicationException("验证码错误");

                var userName = request.Value<string>("userName");
                var password = request.Value<string>("password");
                if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password)) throw new ApplicationException("请输入用户名和密码");

                var user = UserLogic.Login(userName, password);
                if (user != null)
                {

                    System.Web.Security.FormsAuthentication.SetAuthCookie(user.Guid.ToString(), true);
                    LuxDiner.Web.Global.WebContext.CurrentUser = user;
                    return new JsonResult<bool>(true);
                }
            }
            catch (Exception ex)
            {
                errinfo = ex.Message;
                Common.Logger.Error("", ex);
            }
            return new JsonResult<bool>(false, errinfo, false);
        }
    }
}
